package com.ktjy.controller;

import com.ktjy.entity.SysUser;
import com.ktjy.service.SysUserService;
import com.ktjy.utils.Constants;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.aspectj.apache.bcel.classfile.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class LoginController extends BaseController{

    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/lgoin")
    public String toLogin(){
        return forward("/login.jsp");
    }

    @PostMapping("/login")
    public String login(@RequestParam("account") String account,
                        @RequestParam("password") String password,
                        HttpServletRequest request,
                        HttpSession session){
        SysUser loginUser = sysUserService.login(account,password);
        if (loginUser != null){
            session.setAttribute(Constants.SESSION_USER, loginUser);
            return  redirect("/main/index");
        }else {
            request.setAttribute(Constants.REQUEST_ERROR,"用户名或密码错误");
            return forward("/login.jsp");
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return redirect("/login.jsp");
    }

    @GetMapping("/main/index")
    public String index(){
        return "index";
    }

}
